package com.sj.uabrowser.maintabs;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.sj.uabrowser.R;

import java.util.HashMap;

public class MainTab {

    private final static String TAG = "TAB";
    private static final int INITIAL_PROGRESS = 5;
    private static final int MSG_CAPTURE = 42;
    private boolean mWillBeClosed = false;
    private static Bitmap sDefaultFavicon; //默认网站图标

    private long mId = -1;

    // Main WebView wrapper
    private View mContainer;
    // Main WebView
    private Fragment mMainView;
    // Subwindow container
    private View mSubViewContainer;
    // Subwindow WebView
    private Fragment mSubView;

    IUiController mController;

    //
    Context mContext;

    // Saved bundle for when we are running low on memory. It contains the
    // information needed to restore the WebView if the user goes back to the
    // tab.
    private Bundle mSavedState;

    // If true, the tab is in page loading state (after onPageStarted,
    // before onPageFinsihed)
    private boolean mInPageLoad;

    // The last reported progress of the current page
    private int mPageLoadProgress;

    // The time the load started, used to find load page time
    private long mLoadStartTime;

    private int mCaptureWidth;
    private int mCaptureHeight;

    private Bitmap mCapture;
    private Handler mHandler;
    private boolean mUpdateThumbnail;

    public String mSavePageTitle;
    public String mSavePageUrl;
    // save page
    HashMap<Integer, Long> mSavePageJob;
    private PageState mCurrentState;

    // 用来存储页面信息
    static final String ID = "_id";
    static final String CURRENT_URL = "currentUrl";
    static final String CURRENT_TITLE = "currentTitle";
    private boolean mInForeground;
    private static Paint sAlphaPaint = new Paint();
    static {
        sAlphaPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
        sAlphaPaint.setColor(Color.TRANSPARENT);
    }
    // 获取默认网页图标
    private static synchronized Bitmap getDefaultFavicon(Context context) {
        if (sDefaultFavicon == null) {
            sDefaultFavicon = BitmapFactory.decodeResource(
                    context.getResources(), R.drawable.ic_home);
        }
        return sDefaultFavicon;
    }


    public MainTab(Bundle mSavedState) {
        this.mSavedState = mSavedState;
    }

    private void restoreState(Bundle state){
        mSavedState = state;
        if(mSavedState == null){
            return;
        }
        mId = state.getLong(ID);
        String url = state.getString(CURRENT_URL);
        String title = state.getString(CURRENT_TITLE);
        mCurrentState = new MainTab.PageState(mContext,url,title);
    }
    public void shouldUpdateThumbnail(boolean should) {
        mUpdateThumbnail = should;
        if(should) capture();
    }

    /**
     * This is used to get a new ID when the tab has been preloaded, before it is displayed and
     * added to TabControl. Preloaded tabs can be created before restoreInstanceState, leading
     * to overlapping IDs between the preloaded and restored tabs.
     */
    public void refreshIdAfterPreload() {
        mId = MainTabController.getNextId();
    }
    public void updateShouldCaptureThumbnails() {
        synchronized (MainTab.this) {
            if (mCapture == null) {
                mCapture = Bitmap.createBitmap(mCaptureWidth, mCaptureHeight,
                        Bitmap.Config.RGB_565);
                mCapture.eraseColor(Color.WHITE);
            }
        }
    }



    public void capture() {
        if ( mCapture == null) return;
        View view = mController.getActivity().getWindow().getDecorView();
        Canvas c = new Canvas(mCapture);
        int state = c.save();
        view.draw(c);
        c.restoreToCount(state);
        c.setBitmap(null);
        mHandler.removeMessages(MSG_CAPTURE);

    }

    public long getId() {
        return mId;
    }

    public void setFragment(Fragment fragment,Bundle bundle){
        if (mMainView == fragment) {
            return;
        }

        // set the new one
        mMainView = fragment;
        mMainView.onSaveInstanceState(bundle);
    }


    /**
     * Dismiss the subWindow for the tab.
     */
    public void dismissSubWindow() {
        if (mSubView != null) {
            mSubView.onDestroy();
            mSubView = null;
            mSubViewContainer = null;
        }
    }

    public void resume() {
        if (mMainView != null) {
            mMainView.onResume();
            if (mSubView != null) {
                mSubView.onResume();
            }
        }
    }
    public void pause() {
        if (mMainView != null) {
            mMainView.onPause();
            if (mSubView != null) {
                mSubView.onPause();
            }
        }
    }
    public void destroy(){
        if(mMainView!=null){
            mMainView.onDestroy();
        }
    }
    public void putInForeground() {
        if (mInForeground) {
            return;
        }
        mInForeground = true;
        resume();
    }
    public void putInBackground() {
        Log.e(TAG,"putInBackground ------- mInForeground =:" + mInForeground);
        if (!mInForeground) {
            return;
        }
        capture();
        mInForeground = false;
        pause();
    }

    public boolean inForeground() {
        return mInForeground;
    }


    public Fragment getMainView(){
        return mMainView;
    }

    public void setViewContainer(View container) {
        mContainer = container;
    }
    public String getUrl() {
        return mCurrentState.mUrl;
    }

    public boolean checkUrlNotNull(){
        return mCurrentState.checkUrlNotNull();
    }
    public String getOriginalUrl() {
        if (mCurrentState.mOriginalUrl == null) {
            return getUrl();
        }
        return mCurrentState.mOriginalUrl;
    }
    /**
     * Get the title of this tab.
     */
    public String getTitle() {
        if (mCurrentState.mTitle == null && mInPageLoad) {
            return mContext.getString(R.string.title_bar_loading);
        }
        return mCurrentState.mTitle;
    }
    /**
     * Get the favicon of this tab.
     */
    public Bitmap getFavicon() {
        if (mCurrentState.mFavicon != null) {
            return mCurrentState.mFavicon;
        }
        return getDefaultFavicon(mContext);
    }

    public int getPageLoadProgress(){
        return mPageLoadProgress;
    }
    public void clearTabData(){
        mUpdateThumbnail = false;
        mCurrentState.mUrl = "";
        mCurrentState.mOriginalUrl = "";
        mCurrentState.mTitle = mContext.getString(R.string.defaultWebTitle);
        mCurrentState.mFavicon = getDefaultFavicon(mContext);
    }
    /**
     * @return TRUE if onPageStarted is called while onPageFinished is not
     *         called yet.
     */
    boolean inPageLoad() {
        return mInPageLoad;
    }
    /**
     * @return The Bundle with the tab's state if it can be saved, otherwise null
     */
    public Bundle saveState() {
        // If the WebView is null it means we ran low on memory and we already
        // stored the saved state in mSavedState.
        if (mMainView == null) {
            return mSavedState;
        }

        if (TextUtils.isEmpty(mCurrentState.mUrl)) {
            return null;
        }

        mSavedState = new Bundle();

        mSavedState.putLong(ID, mId);
        mSavedState.putString(CURRENT_URL, mCurrentState.mUrl);
        mSavedState.putString(CURRENT_TITLE, mCurrentState.mTitle);
        return mSavedState;
    }
    public Bitmap getScreenshot() {
        synchronized (MainTab.this) {
            return mCapture;
        }
    }

    public static class PageState{
        String mUrl;
        String mOriginalUrl;
        String mTitle;
        Bitmap mFavicon;
        PageState(Context context){
            this(context,"",getDefaultFavicon(context));
        }
        PageState(Context context, String url, Bitmap favicon){
            this(url,context.getString(R.string.defaultWebTitle),favicon);
        }
        PageState(Context context, String url, String title){
            this(url,title,getDefaultFavicon(context));
        }
        PageState(String url, String title, Bitmap favicon){
            mUrl = mOriginalUrl = url;
            mTitle = title;
            mFavicon = favicon;
        }
        boolean checkUrlNotNull(){
            return !TextUtils.isEmpty(mUrl);
        }
    }

}
